<template>
  <div class="left-content">
    <div class="file-search">
      <Icon icon="ant-design:search-outlined" class="icon-search" style="font-size: 16px; display: inline-flex" />
      <a-input v-model:value="search_input" :placeholder="search_placeholder" class="file-search-box" @pressEnter="handleSearch" allowClear />
    </div>
    <ul class="left-file pointer">
      <li
        v-for="item in fileFlagOptions"
        :key="item.fileId"
        :class="item.isSelected ? 'item item-active' : 'item'"
        @mouseover="handleFileFolderMouseOver(item)"
        @mouseleave="handleFileFolderMouseOut(item)"
      >
        <div style="padding: 0px 30px 0px 0px">
          <div style="width: 80%; float: left" @click="handleFileFlagClick(item)">
            <div style="display: flex; align-items: center">
              <Icon :icon="item.icon" :style="item.style" />
              <span style="flex: 1 1 0%">{{ item.fileName }}</span>
              <span style="clear: both"></span>
            </div>
          </div>
          <div style="width: 10%; float: right" v-if="item.isShowSetting && item.isHover">
            <a-dropdown :trigger="['click']" @visible-change="(val) => handleDropdownVisibleChange(val, item)">
              <Icon icon="ant-design:setting-outlined" />
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-for="menuItem in myFilesMenu"
                    :key="menuItem.value"
                    class="left-menu-item"
                    @click="handleMyFilesMenuClick(menuItem.value, item)"
                  >
                    <Icon :icon="menuItem.icon" />
                    {{ menuItem.label }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </div>
      </li>
    </ul>
    <div style="height: 1px; border-bottom: 1px solid rgb(224, 224, 224)"> </div>
    <div class="folder-header" style="margin-top: 10px; display: flex">
      <a-select
        v-model:value="fileOwnershipTypeSel"
        style="width: 150px"
        :options="fileOwnershipTypeOptions"
        @change="handleFileOwnershipTypeChange"
      />
      <Icon
        icon="ant-design:plus-outlined"
        class="add-file-icon"
        style="font-size: 16px; display: inline-flex"
        @click="handleCreateShareFolderClick"
      />
    </div>
    <div v-for="(item, index) in folderOwnershipList" :key="item.folderOwnership.id" class="folder-personal-item">
      <div class="folder-personal-title" @click="handleTenantClick(item)">
        <span class="contentName" style="color: rgba(0, 0, 0, 0.32)">{{ item.folderOwnership.name }}</span>
        <span class="slide" style="color: rgba(0, 0, 0, 0.32)">{{ item.folderOwnership.isExpand ? '关闭' : '展开' }}</span>
      </div>
      <div class="folder-footer">
        <ul>
          <li
            v-for="folder in item.folderList"
            :key="folder.id"
            :class="folder.isSelected ? 'item pointer item-active' : 'item pointer'"
            style="width: 100%; display: flex"
            @mouseover="handleFileFolderMouseOver(folder)"
            @mouseleave="handleFileFolderMouseOut(folder)"
            v-show="folder.isShow"
          >
            <div style="width: 80%; float: left" @click="handleFileFolderClick(folder)">
              <Icon icon="ant-design:folder-open-outlined" style="font-size: 16px; color: rgb(253, 202, 7); display: inline-flex" />
              <span>{{ folder.fileName }}</span>
            </div>
            <div v-if="folder.isHover" style="width: 10%">
              <a-dropdown :trigger="['click']" @visible-change="(val) => handleDropdownVisibleChange(val, folder)">
                <Icon icon="ant-design:setting-outlined" />
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-for="menuItem in folderOwnershipMenu(folder)"
                      :key="menuItem.value"
                      class="left-menu-item"
                      @click="handleFolderOwnershipMenuClick(menuItem.value, folder)"
                    >
                      <Icon :icon="menuItem.icon" />
                      {{ menuItem.label }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div v-else-if="folder.isStar == '1'" style="width: 10%">
              <Icon icon="ant-design:star-filled" style="font-size: 16px; color: rgb(251, 192, 45); display: inline-flex" />
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <FolderShareModal @register="registerFolderShareModal" @success="reloadShareFolder" />
  <FolderLogModal ref="folderLogRef" />
  <FolderRemoveModal ref="folderRemoveRef" @success="reloadShareFolder" />
  <FolderExitModal ref="folderExitRef" @success="reloadShareFolder" />
</template>

<script lang="ts">
  import { defineComponent, ref, unref, reactive, watch, onMounted, nextTick } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import FolderShareModal from './FolderShareModal.vue';
  import FolderLogModal from './FolderLogModal.vue';
  import FolderRemoveModal from './FolderRemoveModal.vue';
  import FolderExitModal from './FolderExitModal.vue';
  import { generateMyFile, getUserTenants, getIsRootFolderList, changeStar } from '../files.api';
  import { fileFlagOptions, myFilesMenu, fileOwnershipTypeOptions, folderOwnershipMenu, fileCreateMenu } from '../files.data';

  export default defineComponent({
    name: 'LeftFile',
    components: { FolderShareModal, FolderLogModal, FolderRemoveModal, FolderExitModal },
    props: {
      isExpand: { type: Boolean, default: true },
    },
    emits: ['dataChange', 'search', 'allowAddFile'],
    setup(props, { emit }) {
      const userStore = useUserStore();
      const folderRemoveRef = ref();
      const folderLogRef = ref();
      const folderExitRef = ref();
      const fileUploadRef = ref();
      const fileLinkRef = ref();

      const rightFileRef = ref();
      const fileAttributeRef = ref();
      // 当前登录人ID
      const userId = userStore.getUserInfo.id;
      // 搜索框输入的文本
      const search_input = ref('');
      const search_placeholder = ref('');
      // 文件归属类型
      const fileOwnershipTypeSel = ref('0');
      // 目录分类
      const folderOwnershipList = reactive([]);
      // 目录路径
      const folderPathList = ref([]);
      // 是否允许在当前目录下添加文件
      const isAllowAddFile = ref(true);
      // 文件搜索条件
      const searchParams = { type: null, parentId: null, isRecycleBin: false };

      const { createMessage: $message } = useMessage();
      //共享目录modal
      const [registerFolderShareModal, { openModal: openShareModal }] = useModal();

      onMounted(() => {
        nextTick(() => {
          loadCurrentUserFolderOwnership();
          handleFileFlagClick(fileFlagOptions[0]);
        });
      });

      // isAllowAddFile 变化，通知
      watch(
        () => isAllowAddFile,
        async () => {
          if (isAllowAddFile.value) {
            emit('allowAddFile', true);
          } else {
            emit('allowAddFile', false);
          }
        },
        { deep: true, immediate: true }
      );

      // 加载文件夹归属目录
      async function loadCurrentUserFolderOwnership() {
        const data = await getUserTenants();
        if (data && data.list) {
          data.list.forEach((item) => {
            folderOwnershipList.push({
              folderOwnership: {
                id: item.id,
                name: item.name,
                isExpand: false,
                isShow: true,
              },
              folderList: [],
            });
          });
        }

        folderOwnershipList.push({
          folderOwnership: {
            id: '个人',
            name: '个人',
            isExpand: true,
            isShow: true,
          },
          folderList: [],
        });

        reloadRootFolderList();

        setFolderOwnershipIfShow();
      }

      // 重新加载一级目录
      async function reloadRootFolderList() {
        folderOwnershipList.forEach((item) => {
          if (item.folderOwnership.isExpand) {
            loadRootFolderList(item);
          }
        });
      }

      // 加载一级目录-根据文档拥有类型
      async function loadRootFolderList(folderOwnershipItem) {
        const params = {
          folderOwnership: folderOwnershipItem.folderOwnership.id,
          userId: userId,
        };
        const data = await getIsRootFolderList(params);
        folderOwnershipItem.folderList = [];
        data.forEach((item) => {
          folderOwnershipItem.folderList.push({
            // 文件或文件目录ID
            fileId: item.id,
            // 文件或文件目录名
            fileName: item.fileName,
            // 权限 owner、admin、editable、readonly
            authority: item.authority,
            // 是否标星
            isStar: item.isStar,
            // 是否显示
            isShow: true,
            // 是否被鼠标悬停
            isHover: false,
            // 是否被选中
            isSelected: false,
            // 是否下拉菜单已展示
            dropdownVisible: false,
          });
        });
      }

      // 左侧-共享目录-根据选择的租户展示租户所拥有的共享目录
      async function setFolderOwnershipIfShow() {
        folderOwnershipList.forEach((item) => {
          if (fileOwnershipTypeSel.value == '1') {
            item.folderList.forEach((p) => {
              p.isShow = p.authority == 'owner';
            });
          } else if (fileOwnershipTypeSel.value == '2') {
            item.folderList.forEach((p) => {
              p.isShow = p.authority != 'owner';
            });
          } else {
            item.folderList.forEach((p) => {
              p.isShow = true;
            });
          }

          if (item.folderOwnership.id == '个人') {
            item.folderOwnership.isShow = true;
          } else {
            let hasList = item.folderList.filter((item) => item.isShow == true);
            if (unref(hasList).length > 0) {
              item.folderOwnership.isShow = true;
            } else {
              item.folderOwnership.isShow = false;
            }
          }
        });
      }

      // 左侧-顶部-查询功能
      async function handleSearch() {
        emit('search', search_input.value);
      }

      // 左侧-共享目录-重新加载
      async function reloadShareFolder() {
        reloadRootFolderList();
      }

      // 左侧-文件分类（我的文件、最近使用、星标文件）-点击事件
      async function handleFileFlagClick(record) {
        if (record.fileId == '0') {
          isAllowAddFile.value = true;
        } else {
          isAllowAddFile.value = false;
        }
        await leftFolderTypeItemActive(record.fileId);
        await commonFolderClick(record.fileId, record.fileName, false);
      }

      // 左侧-文件点击后变为选中状态
      async function leftFolderTypeItemActive(val) {
        fileFlagOptions.forEach((item) => {
          if (item.fileId == val) {
            item.isSelected = true;
          } else {
            item.isSelected = false;
          }
        });
        folderOwnershipList.forEach((folderOwnershipItem) => {
          folderOwnershipItem.folderList.forEach((item) => {
            if (item.fileId == val) {
              item.isSelected = true;
            } else {
              item.isSelected = false;
            }
          });
        });
      }

      // 左侧-共享文件夹-拥有类型切换事件
      async function handleFileOwnershipTypeChange() {
        setFolderOwnershipIfShow();
      }

      // 左侧-共享文件夹-添加共享目录
      async function handleCreateShareFolderClick() {
        openShareModal(true, {
          isUpdate: false,
        });
      }

      // 左侧-共享文件夹-租户点击事件（个人、其他租户）
      async function handleTenantClick(record) {
        record.folderOwnership.isExpand = !record.folderOwnership.isExpand;
        if (item.folderOwnership.isExpand) {
          loadRootFolderList(record);
        } else {
          record.folderList = [];
        }
      }

      // 左侧-共享文件夹-点击事件
      async function handleFileFolderClick(record) {
        isAllowAddFile.value = true;
        await leftFolderTypeItemActive(record.fileId);
        await commonFolderClick(record.fileId, record.fileName, false);
      }

      // 左侧-共享文件夹-鼠标移入
      async function handleFileFolderMouseOver(record) {
        record.isHover = true;
      }

      // 左侧-共享文件夹-鼠标移出
      async function handleFileFolderMouseOut(record) {
        if (record.dropdownVisible) {
          return;
        }
        record.isHover = false;
      }

      // 左侧-共享文件夹-下拉菜单显示变更事件
      async function handleDropdownVisibleChange(val, record) {
        record.dropdownVisible = val;
        if (record.dropdownVisible) {
          record.isHover = true;
        } else {
          record.isHover = false;
        }
      }

      // 左侧-文件分类（我的文件、最近使用、星标文件）-下拉菜单-点击事件
      async function handleMyFilesMenuClick(key, record) {
        record.isHover = false;
        switch (key) {
          case 'log':
            const result = await getGenerateMyFile(record.fileName);
            folderLogRef.value.showModal({ fileId: result.data.id, fileName: result.data.fileName });
            break;
          case 'recycle':
            isAllowAddFile.value = false;
            await commonFolderClick(record.fileId, record.fileName, true);
            break;
        }
      }

      // 左侧-共享文件夹-下拉菜单-点击事件
      async function handleFolderOwnershipMenuClick(key, record) {
        record.isHover = false;
        record.dropdownVisible = false;
        switch (key) {
          case 'star':
            setStar(record);
            break;
          case 'team':
            openShareModal(true, {
              isUpdate: true,
              record,
            });
            break;
          case 'log':
            folderLogRef.value.showModal(record);
            break;
          case 'recycle':
            isAllowAddFile.value = false;
            await commonFolderClick(record.fileId, record.fileName, true);
            break;
          case 'del':
            folderRemoveRef.value.showModal(record);
            break;
          case 'exit':
            folderExitRef.value.showModal(record);
            break;
        }
      }

      /**
       * 标星
       */
      async function setStar(record) {
        const starFlag = record.isStar == '1' ? '0' : '1';
        const params = { fileId: record.fileId, isStar: starFlag };
        await changeStar(params, function () {
          record.isStar = starFlag;
        });
      }

      /**
       * 生成我的目录
       */
      async function getGenerateMyFile(name) {
        const res = await generateMyFile({
          isDel: '0',
          downCount: 0,
          fileName: name,
          fileType: 'folder',
          isFolder: '1',
          isRootFolder: '1',
          parentId: '',
          readCount: 0,
          storeType: 'manage',
        });
        return res;
      }

      /**
       * 根目录点事件-包括我的文件、最近使用文件、标星文件、租户目录
       * fileId:目录ID
       * fileName:目录名
       * isRecycleBin:是否为回收站
       */
      async function commonFolderClick(fileId, fileName, isRecycleBin) {
        if (0 == fileId) {
          //我的文件夹
          const res = await getGenerateMyFile(fileName);
          searchParams.type = '';
          folderPathList.value = [
            {
              fileId: res.data ? res.data.id : '',
              fileName: res.data ? res.data.fileName : '',
            },
          ];
        } else if (1 == fileId) {
          //最近使用文件
          searchParams.type = 'used';
          folderPathList.value = [];
        } else if (2 == fileId) {
          //标星文件
          searchParams.type = 'star';
          folderPathList.value = [];
        } else {
          //租户共享目录或个人共享目录
          searchParams.type = '';
          folderPathList.value = [
            {
              fileId: fileId,
              fileName: fileName,
            },
          ];
        }
        searchParams.isRecycleBin = isRecycleBin;
        if (folderPathList.value.length > 0) {
          searchParams.fileId = folderPathList.value[0].fileId;
          searchParams.fileName = folderPathList.value[0].fileName;
        } else {
          searchParams.fileId = '';
          searchParams.fileName = '';
        }
        emit('dataChange', cloneDeep(folderPathList.value), cloneDeep(searchParams));
      }

      /**
       * 设置搜索输入框内容
       */
      async function setSearchInput(fileName, clear) {
        if (fileName) {
          search_placeholder.value = '在"' + fileName + '"条件中搜索';
        } else {
          search_placeholder.value = '';
        }
        if (clear) {
          search_input.value = '';
        }
      }

      return {
        registerFolderShareModal,
        folderLogRef,
        folderRemoveRef,
        folderExitRef,
        fileUploadRef,
        fileLinkRef,
        rightFileRef,
        fileAttributeRef,
        fileFlagOptions,
        myFilesMenu,
        fileOwnershipTypeOptions,
        folderOwnershipMenu,
        fileCreateMenu,
        fileOwnershipTypeSel,
        folderOwnershipList,
        search_input,
        search_placeholder,
        isAllowAddFile,
        handleSearch,
        handleFileFlagClick,
        handleMyFilesMenuClick,
        handleFolderOwnershipMenuClick,
        handleCreateShareFolderClick,
        handleTenantClick,
        handleFileFolderClick,
        handleFileFolderMouseOver,
        handleFileFolderMouseOut,
        handleFileOwnershipTypeChange,
        handleDropdownVisibleChange,
        reloadShareFolder,
        setSearchInput,
      };
    },
  });
</script>

<style lang="less" scoped>
  @import '../less/LeftFile';
</style>
